/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.config;

import exatrez.model.User;
import exatrez.model.UserGroup;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.security.controller.StripesSecurityManager;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author fikri
 */
public class SecurityManager implements StripesSecurityManager{
    
    private static final Logger LOG = Logger.getLogger(SecurityManager.class);
    private static boolean isDebug = LOG.isDebugEnabled();

    @Override
     public boolean isUserInRole(List<String> roles, ActionBeanContext context) {    
        if (roles == null || roles.isEmpty()) {
            return false;
        }
        ableActionBeanContext ctx = (ableActionBeanContext)context;
        User pengguna = ctx.getCurrentUser();
         if (pengguna == null){
             return false;
         }

        if (isDebug) {
            LOG.debug("pengguna = " + pengguna.getUserId());
        }

        String[] rolesList = (String[])roles.toArray();        

        try{          
            List<UserGroup> peranans = pengguna.getRoles();
            
            for(int i=0; i<peranans.size(); i++) {
                UserGroup peranan = (UserGroup)peranans.get(i);
                if (isDebug) LOG.info("peranan " + peranan.getGroup().getGroupId());
                if (ArrayUtils.contains(rolesList, String.valueOf(peranan.getGroup().getGroupId()))) return true;
            }
            
        }catch (Exception ex) {
            LOG.error(ex);
        } 
        return false;
//        return true;
    }

    @Override
    public boolean isUserInRole(List<String> list, HttpServletRequest hsr, HttpServletResponse hsr1) {
        return true;
    }
    
}
